package com.forlove.app.qselect.index.ui;

import android.content.Intent;
import android.content.res.Resources;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatImageView;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseFragment;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.widget.CircleImageView;
import com.forlove.app.event.ActiveFlagEvent;
import com.forlove.app.event.EventEntity;
import com.forlove.app.manager.EventManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.qselect.MainActivity;
import com.forlove.app.qselect.MainTabView;
import com.forlove.app.qselect.index.presenter.IndexFragmentPresenter;
import com.forlove.app.qselect.index.view.IndexFragmentView;
import com.forlove.app.qselect.login.entity.UserEntity;

import java.lang.reflect.Field;
import java.util.ArrayList;

import butterknife.BindView;

/**
 * 首页fragment
 * Created by yjl on 2017/9/28.
 */

public class IndexFragment extends BaseFragment<IndexFragmentPresenter> implements
        ViewPager.OnPageChangeListener,
        IndexFragmentView, MainTabView.ActiveFlagListener {
    public static final int POSITION_INDEX_FRIEND = 0;//首页好友
    public static final int POSITION_INDEX_MiNE = 1;//首页我的
    private static int mPosition = POSITION_INDEX_MiNE;
    @BindView(R.id.view_toolbar)
    RelativeLayout view_toolbar; //首页的toolbar

    @BindView(R.id.tx_hot_num)
    TextView tx_hot_num;  //首页钻石数目

    @BindView(R.id.index_tab)
    TabLayout index_tab; //首页的tab
    @BindView(R.id.viewpager_index)
    ViewPager viewPager;

    @BindView(R.id.toolbar_right_icon)
    AppCompatImageView toolbar_right_icon;

    @BindView(R.id.image_mine)
    CircleImageView image_mine;

    @BindView(R.id.view_new_info)
    View view_new_info;

    @BindView(R.id.view_unread_num)
    TextView view_unread_num;

    private TabAdapter tabAdapter;

    private ArrayList<BaseFragment> fragmentList = new ArrayList<>();
    private final int[] TAB_TITLES = new int[]{R.string.index_friend, R.string.index_mine};

    @Override
    public int getLayoutId() {
        return R.layout.fragment_index;
    }

    private UserEntity userEntity;

    @Override
    protected void initFragmentView() {
        LogUtil.e("yjl", "IndexFragment initFragmentView:" + MainActivity.getCurrentPosition());
        if (!isInit && MainActivity.getCurrentPosition() == MainActivity.POSITION_INDEX) {
//            initTitleBar();
            initFragment();
            isInit = true;
        }

    }

    public static int getPos() {
        return mPosition;
    }

    public static void setPos(int pos) {
        if (pos > -1) {
            mPosition = pos;
        }
    }

    private void initFragment() {
        if (presenter == null) {
            presenter = new IndexFragmentPresenter(this);
        }
        if (fragmentList.size() == 0) {
            fragmentList.clear();
            FriendCircleInfoFragment friendCircleInfoFragment = new FriendCircleInfoFragment();
            fragmentList.add(POSITION_INDEX_FRIEND, friendCircleInfoFragment);
            MineCircleInfoFragment mineCircleInfoFragment = new MineCircleInfoFragment();
            fragmentList.add(POSITION_INDEX_MiNE, mineCircleInfoFragment);
            tabAdapter = new TabAdapter(getChildFragmentManager());
            viewPager.setAdapter(tabAdapter);
            viewPager.addOnPageChangeListener(this);
            viewPager.setCurrentItem(mPosition);
            index_tab.setupWithViewPager(viewPager);
            index_tab.post(new Runnable() {
                @Override
                public void run() {
                    setIndicator(index_tab, 45, 45);
                }
            });
            FriendCircleInfoFragment.setActiveFlagListener(this);
            MineCircleInfoFragment.setActiveFlagListener(this);
        }

        userEntity = UserManager.getUesrInfo(mContext);

        tx_hot_num.setText(userEntity.diamond + "");
        presenter.loadImageView(
                mContext, image_mine, userEntity.mUserImage,
                R.mipmap.image_mine_friend_avatar);
        image_mine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext, MineInfoActivity.class));
            }
        });
    }


    @Override
    public void onSelected(int pos) {
        if (MainActivity.getCurrentPosition() == MainActivity.POSITION_INDEX) {
            LogUtil.e("yjl", "IndexFragment:" + pos);
            if (getView() == null && getActivity() != null) {
                mContext = getActivity();
                initFragment();
            } else if (!isInit && getView() != null) {
                mContext = getActivity();
                initFragmentView();
            } else if (isInit && getView() != null) {
                viewPager.setCurrentItem(mPosition);
            }
        }
    }


    private class TabAdapter extends FragmentPagerAdapter {
        public TabAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
//            if (position >= TAB_TITLES.length) {
//                position = TAB_TITLES.length - 1;
//            }
            return getResources().getString(TAB_TITLES[position]);
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }
    }

    /**
     * 修改tablayout 底部线条宽度
     *
     * @param tabs
     * @param leftDip
     * @param rightDip
     */
    public void setIndicator(TabLayout tabs, int leftDip, int rightDip) {

        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(final int position) {
        //indexfragment 内部切换
        if (position == mPosition) {
            return;
        }
        LogUtil.e("yjl", "onPageSelected:" + position);
        mPosition = position;
        fragmentList.get(position).onSelected(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onDestroy() {
        if (fragmentList != null && fragmentList.size() > 0) {
            fragmentList.clear();
        }
        super.onDestroy();

    }

    private boolean isRefresh() {
        if ((mPosition == IndexFragment.POSITION_INDEX_FRIEND && FriendCircleInfoFragment.hasNewFriend)
                || (mPosition == IndexFragment.POSITION_INDEX_MiNE && MineCircleInfoFragment.unReadNum > 0)) {

            return true;
        }
        return false;
    }

    private void showUnreadNum(int unread) {
        view_unread_num.setVisibility(View.VISIBLE);
        if (unread > 99) {
            view_unread_num.setText(99 + "+");
        } else {
            view_unread_num.setText(unread + "");
        }
    }

    private void hideUnreadNum() {
        view_unread_num.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onEvent(EventEntity event) {
        LogUtil.e("yjl", "indexfragment eventEntity id:" + event.eventId + "    name:" + event.eventName);
        if (event != null && event.eventId == EventManager.EVENT_UPDATE_USERINFO) {
            userEntity = UserManager.getUesrInfo(getContext());
            if (userEntity != null) {
                if (tx_hot_num != null) {
                    tx_hot_num.setText(userEntity.diamond + "");
                }
                if (presenter != null && image_mine != null)
                    presenter.loadImageView(
                            mContext, image_mine, userEntity.mUserImage,
                            R.mipmap.image_mine_friend_avatar);
            }
        } else if (event != null && event.eventId == EventManager.EVENT_NEW_FLAG) {
            if (event instanceof ActiveFlagEvent) {
                ActiveFlagEvent activeFlagEvent = (ActiveFlagEvent) event;
                if (MineCircleInfoFragment.unReadNum > 0) {
                    showUnreadNum(MineCircleInfoFragment.unReadNum);
                } else {
                    hideUnreadNum();
                }

                int oldId = UserManager.getNewCircleInfo(getContext());
                if (activeFlagEvent.lastRecord > oldId) {
                    FriendCircleInfoFragment.hasNewFriend = true;
                    view_new_info.setVisibility(View.VISIBLE);
                } else {
                    FriendCircleInfoFragment.hasNewFriend = false;
                    view_new_info.setVisibility(View.INVISIBLE);
                }
            }
        }
    }

    @Override
    public void readMineCircle(int unread) {
        if (unread > 0) {
            showUnreadNum(unread);
        } else {
            hideUnreadNum();
        }
    }

    @Override
    public void readFriendCircleInfo(boolean isShow) {
        if (isShow) {
            view_new_info.setVisibility(View.VISIBLE);
        } else {
            view_new_info.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void readNewFriendInfo(boolean isShow) {

    }

//    @MLinkRouter(keys={"quanyiquan_key"})
//    public class DetailActivity extends Activity {
//        @Override
//        public void onCreate(Bundle savedInstanceState) {
//            super.onCreate(savedInstanceState);
//
//            //通过intent方式获取动态参数值
//            Intent intent = getIntent();
//            if (intent != null) {
//                String param = intent.getStringExtra("param");
//            }
//        }
//    }
}
